#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
检查test用户的角色数据和挂机配置
"""

from database import db_manager
from datetime import datetime

def check_test_user_data():
    """
    检查test用户的完整数据配置
    """
    print("=== 检查test用户数据配置 ===")
    
    try:
        # 1. 检查账号信息
        print("\n1. 账号信息:")
        account_query = "SELECT id, username, email, created_at FROM accounts WHERE username = %s"
        account_result = db_manager.execute_query(account_query, ('test',))
        
        if not account_result:
            print("❌ 未找到test账号")
            return
        
        account = account_result[0]
        account_id = account['id']
        print(f"✅ 账号ID: {account_id}")
        print(f"   用户名: {account['username']}")
        print(f"   邮箱: {account['email']}")
        print(f"   创建时间: {account['created_at']}")
        
        # 2. 检查角色信息
        print("\n2. 角色信息:")
        character_query = """
            SELECT id, name, character_class, level, exp, exp_to_next_level,
                   strength, agility, intelligence, vitality,
                   is_idle, is_in_battle, battle_id, created_at
            FROM characters 
            WHERE account_id = %s
        """
        character_result = db_manager.execute_query(character_query, (account_id,))
        
        if not character_result:
            print("❌ 未找到角色")
            return
        
        characters = character_result
        print(f"✅ 找到 {len(characters)} 个角色:")
        
        for char in characters:
            char_id = char['id']
            print(f"\n   角色ID: {char_id}")
            print(f"   角色名: {char['name']}")
            print(f"   职业: {char['character_class']}")
            print(f"   等级: {char['level']}")
            print(f"   当前经验: {char['exp']}")
            print(f"   升级所需经验: {char['exp_to_next_level']}")
            print(f"   力量: {char['strength']}")
            print(f"   敏捷: {char['agility']}")
            print(f"   智力: {char['intelligence']}")
            print(f"   体力: {char['vitality']}")
            print(f"   是否挂机中: {char['is_idle']}")
            print(f"   是否战斗中: {char['is_in_battle']}")
            print(f"   战斗ID: {char['battle_id']}")
            print(f"   创建时间: {char['created_at']}")
            
            # 3. 检查挂机记录
            print(f"\n   挂机记录 (角色ID: {char_id}):")
            idle_query = """
                SELECT id, location_id, start_time, end_time, status, 
                       exp_gained, duration_seconds
                FROM idle_records 
                WHERE character_id = %s 
                ORDER BY start_time DESC 
                LIMIT 5
            """
            idle_result = db_manager.execute_query(idle_query, (char_id,))
            
            if idle_result:
                print(f"   ✅ 找到 {len(idle_result)} 条挂机记录:")
                for i, record in enumerate(idle_result, 1):
                    print(f"     记录{i}:")
                    print(f"       ID: {record['id']}")
                    print(f"       地点ID: {record['location_id']}")
                    print(f"       开始时间: {record['start_time']}")
                    print(f"       结束时间: {record['end_time']}")
                    print(f"       状态: {record['status']}")
                    print(f"       获得经验: {record['exp_gained']}")
                    print(f"       持续时间(秒): {record['duration_seconds']}")
                    
                    # 检查当前活跃的挂机记录
                    if record['status'] == 'active':
                        print(f"       ⚠️  当前活跃挂机记录")
                        
                        # 计算挂机时长
                        if record['start_time']:
                            duration = datetime.now() - record['start_time']
                            duration_hours = duration.total_seconds() / 3600
                            print(f"       当前挂机时长: {duration_hours:.2f} 小时")
            else:
                print("   ❌ 未找到挂机记录")
            
            # 4. 检查挂机地点信息
            print(f"\n   挂机地点信息:")
            location_query = """
                SELECT DISTINCT il.id, il.name, il.description, il.base_exp_rate, 
                       il.min_level, il.max_level, il.location_type, il.is_active
                FROM idle_locations il
                JOIN idle_records ir ON il.id = ir.location_id
                WHERE ir.character_id = %s
            """
            location_result = db_manager.execute_query(location_query, (char_id,))
            
            if location_result:
                print(f"   ✅ 角色使用过的挂机地点:")
                for loc in location_result:
                    print(f"     地点ID: {loc['id']}")
                    print(f"     地点名: {loc['name']}")
                    print(f"     描述: {loc['description']}")
                    print(f"     基础经验率: {loc['base_exp_rate']}")
                    print(f"     最低等级: {loc['min_level']}")
                    print(f"     最高等级: {loc['max_level']}")
                    print(f"     地点类型: {loc['location_type']}")
                    print(f"     是否开放: {loc['is_active']}")
            else:
                print("   ❌ 未找到使用过的挂机地点")
        
        # 5. 检查数据一致性
        print("\n3. 数据一致性检查:")
        
        # 检查是否有孤立的挂机记录
        orphan_idle_query = """
            SELECT ir.id, ir.character_id
            FROM idle_records ir
            LEFT JOIN characters c ON ir.character_id = c.id
            WHERE c.id IS NULL
        """
        orphan_idle_result = db_manager.execute_query(orphan_idle_query)
        
        if orphan_idle_result:
            print(f"   ⚠️  发现 {len(orphan_idle_result)} 条孤立的挂机记录")
            for record in orphan_idle_result:
                print(f"     挂机记录ID: {record['id']}, 角色ID: {record['character_id']}")
        else:
            print("   ✅ 没有孤立的挂机记录")
        
        # 检查是否有多个活跃挂机记录
        active_idle_query = """
            SELECT character_id, COUNT(*) as count
            FROM idle_records
            WHERE status = 'active'
            GROUP BY character_id
            HAVING COUNT(*) > 1
        """
        active_idle_result = db_manager.execute_query(active_idle_query)
        
        if active_idle_result:
            print(f"   ⚠️  发现角色有多个活跃挂机记录:")
            for record in active_idle_result:
                print(f"     角色ID: {record['character_id']}, 活跃记录数: {record['count']}")
        else:
            print("   ✅ 每个角色最多只有一个活跃挂机记录")
        
        # 检查角色状态与挂机记录的一致性
        status_check_query = """
            SELECT c.id, c.name, c.is_idle, 
                   COUNT(ir.id) as active_idle_count
            FROM characters c
            LEFT JOIN idle_records ir ON c.id = ir.character_id AND ir.status = 'active'
            WHERE c.account_id = %s
            GROUP BY c.id, c.name, c.is_idle
        """
        status_check_result = db_manager.execute_query(status_check_query, (account_id,))
        
        print("   角色状态与挂机记录一致性:")
        for record in status_check_result:
            is_idle = record['is_idle']
            active_count = record['active_idle_count']
            
            if is_idle and active_count == 1:
                print(f"     ✅ 角色 {record['name']}: 挂机状态={is_idle}, 活跃挂机记录={active_count}")
            elif not is_idle and active_count == 0:
                print(f"     ✅ 角色 {record['name']}: 挂机状态={is_idle}, 活跃挂机记录={active_count}")
            else:
                print(f"     ⚠️  角色 {record['name']}: 挂机状态={is_idle}, 活跃挂机记录={active_count} (不一致)")
        
        print("\n=== 检查完成 ===")
        
    except Exception as e:
        print(f"❌ 检查过程中发生错误: {e}")
        import traceback
        traceback.print_exc()

if __name__ == "__main__":
    check_test_user_data()